package com.kylin.artwork.manage.starter.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kylin.artwork.manage.starter.security.JwtTokenProvider;
import com.kylin.shared.common.consts.Constants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年07月30日 10:04
 */
@Slf4j
@RequiredArgsConstructor
public class KylinJwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final ObjectMapper mapper = new ObjectMapper();
    private final JwtTokenProvider tokenProvider;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if(!request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                && !request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            return super.attemptAuthentication(request, response);
        }

        UsernamePasswordAuthenticationToken authToken = null;
        try (InputStream is = request.getInputStream()) {
            User authenticationBean = mapper.readValue(is, User.class);
            authToken = new UsernamePasswordAuthenticationToken(
                    authenticationBean.getUsername(), authenticationBean.getPassword());
        } catch (IOException e) {
            log.error("filter:{0}", e);
            authToken = new UsernamePasswordAuthenticationToken(
                    Constants.STR_EMPTY, Constants.STR_EMPTY);
        } finally {
            setDetails(request, authToken);
        }
        return getAuthenticationManager().authenticate(authToken);
    }

    /**
     * 成功验证后调用的方法
     * 如果验证成功，就生成token并返回
     **/
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authentication) throws IOException, ServletException {

        User kylinUserDetails = (User) authentication.getPrincipal();
        System.out.println("kylinUserDetails:" + kylinUserDetails.toString());

        String token = tokenProvider.generateToken(kylinUserDetails);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("token", token);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response,
                                              AuthenticationException failed) throws IOException, ServletException {
        response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    }
}
